package edu.uba.fcen.estimacion.cubrimiento.estrategias;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.uba.fcen.estimacion.word.selection.constants.Constants;
import edu.uba.fcen.estimacion.word.selection.filter.FilterWords;
import edu.uba.fcen.estimacion.word.selection.filter.FilterWordsFactory;

/**
 *  Es equivalente a {@link DistinctAndUniqueWordsStrategy}
 *	Se corresponde con el pseudo-código
 *
 *	- palabrasEnElSD = 0
 *	- palabrasTotales = 0
 *	- por cada lema de cada palabra en TI 
 * 		- si el lema no fue considerado previamente
 *			- si el lema pertenece al SD entonces
 *				- palabrasEnElSD++
 *			- palabrasTotales++
 *			- agregar el lema entre los considerados
 *	- retornar palabrasEnElSD / palabrasTotales
 *
 */
@Deprecated
public class AllNewWordsStrategy implements CoverageStrategy {

	private Map<String, Double> topWords;
	private File fileWhereApplyCoverage;

	public AllNewWordsStrategy(File aFileWhereApplyCoverage, Map<String, Double> topWords) {
		this.fileWhereApplyCoverage = aFileWhereApplyCoverage;
		this.topWords = topWords;
	}
	
	@Override
	public double cover() {
		FilterWords fw = FilterWordsFactory.getNormalLineByLineFilter(this.fileWhereApplyCoverage.getAbsolutePath());
		String line, lemma, tag, lemmaWithTag;
		String[] splited;
		long wordsInTheDataSet = 0l;
		long totalWords = 0l;
		Map<String, Object> allNewWords = new HashMap<String, Object>();

		while ((line=fw.readLine())!=null) {
			if (line.contains("+(") && line.contains("-)")) {
				splited = line.split(Constants.WHITE_SPACE);
				for (int i = 0; i < splited.length; i++) {
					if (splited[i].length()>0) {
						if (splited[i].startsWith("+(")) {
							lemma = splited[i+1];
							tag = splited[i+2];
							lemmaWithTag = lemma +"_" + tag.charAt(0);
							final boolean isOldWord = allNewWords.containsKey(lemmaWithTag);
							if (isWord(lemma) && !isOldWord) {
								if (this.topWords.containsKey(lemmaWithTag) ) {
									wordsInTheDataSet++;
								}
								allNewWords.put(lemmaWithTag, 1);
								totalWords++;
							}
						}
					}
				}
			}
		}
		return (double) wordsInTheDataSet/totalWords;
	}

	private boolean isWord(String lemma) {
		Pattern patternPunctuation = Pattern.compile(Constants.PUNCTUATION_SYMBOL, Pattern.UNICODE_CASE);
		Matcher match = patternPunctuation.matcher(lemma);
		return !match.find();
	}
}
